package datas

import (
	"encoding/json"
	"log"
	"net"
	"strings"
)

const (
	SEP = "<SEP>"
)

func InputJson(conn net.Conn, pre string, suggests G) (r string, err error) {
	buf, _ := json.Marshal(Gi{
		"label":   pre,
		"options": suggests,
	})
	_, err = conn.Write([]byte("repls:" + string(buf)))
	if err != nil {
		log.Println("Send msg error:", err)
		return
	}
	buf = make([]byte, 4096)
	var n int
	n, err = conn.Read(buf)
	if err != nil {
		log.Println("Repl Msg err:", err)
	}
	r = string(buf[:n])
	return
}

func FunctionJson(conn net.Conn, key string, suggests G) (r string, err error) {
	buf, _ := json.Marshal(Gi{
		"label":   key,
		"options": suggests,
		"toggle":  true,
	})
	_, err = conn.Write([]byte("replf:" + string(buf)))
	if err != nil {
		log.Println("Send msg error:", err)
		return
	}
	buf = make([]byte, 4096)
	var n int
	n, err = conn.Read(buf)
	if err != nil {
		log.Println("Repl Msg err:", err)
	}
	r = string(buf[:n])
	return
}

func Choose(conn net.Conn, pre string, options ...string) (r string, err error) {
	_, err = conn.Write([]byte("list:" + pre + SEP + strings.Join(options, "\n")))
	if err != nil {
		log.Println("Send msg error:", err)
		return
	}
	buf := make([]byte, 4096)
	var n int
	n, err = conn.Read(buf)
	if err != nil {
		log.Println("Repl Msg err:", err)
	}
	r = string(buf[:n])
	return
}
